﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Xna.Framework.Input.Touch;

namespace TM.QWeibo.Client.UserControls
{
    public partial class SearchTweet : UserControl
    {
        public SearchTweet()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 拉取数据类型
        /// </summary>
        private enum EPollType
        {
            /// <summary>
            /// 默认，结果绑定到控件
            /// </summary>
            Default,
            /// <summary>
            /// 下一页，结果追加到末尾
            /// </summary>
            NextPage,
            /// <summary>
            /// 最新，结果插到开头
            /// </summary>
            Lastest
        }

        #region 本控件事件

        private Action beforeLoadingCallback { get; set; }

        private Action<object> afterLoadedCallback { get; set; }

        /// <summary>
        /// 选择微博
        /// </summary>
        public Action<SDK.Objects.Tweet> Selected { get; set; }

        /// <summary>
        /// 获取最新之后的回调
        /// </summary>
        public Action GotLastest { get; set; }

        #endregion

        #region 操作事件

        /// <summary>
        /// 选择查看的微博
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TweetListBox_Tap(object sender, GestureEventArgs e)
        {
            var u = (SDK.Objects.Tweet)TweetListBox.SelectedItem;
            if (Selected != null && u != null)
            {
                Selected(u);
            }
        }

        /// <summary>
        /// 手势是否是垂直拖拽
        /// </summary>
        private bool isVerticalDrag { get; set; }

        /// <summary>
        /// 手势结束
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureCompleted(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            if (isVerticalDrag || AppSetting.HightDragSensitivity)
            {
                var scrollviewer = AppSetting.FindChildOfType<ScrollViewer>(TweetListBox);
                if (scrollviewer == null)
                {
                    return;
                }
                //到底部
                if (Math.Abs(scrollviewer.VerticalOffset - scrollviewer.ScrollableHeight) < 2)
                {
                    GetNextPage();
                }
            }
        }
        /// <summary>
        /// 手势开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GestureListener_GestureBegin(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
        {
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gs = TouchPanel.ReadGesture();
                if (gs.GestureType == GestureType.VerticalDrag)
                {
                    isVerticalDrag = true;
                }
            }
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 是否还有下一页
        /// </summary>
        private bool hasNext { get; set; }
        /// <summary>
        /// 是否正在拉取数据
        /// </summary>
        private bool isPolling { get; set; }

        private string _keyword { get; set; }

        /// <summary>
        /// 当前页码
        /// </summary>
        private int pageIndex { get; set; }

        /// <summary>
        /// 下一页
        /// </summary>
        private void GetNextPage()
        {

            if (!this.IsCanPollData()) return;

            if (!hasNext)
            {
                return;
            }

            if (beforeLoadingCallback != null)
            {
                beforeLoadingCallback();
            }

            isPolling = true;

            pageIndex++;
            Dal.Tweet.Instance.Search(_keyword, pageIndex, GetFansListEnd);

            Dispatcher.BeginInvoke(() =>
            {
                if (!TweetListBox.ShowListFooter)
                {
                    TweetListBox.ShowListFooter = true;
                    TweetListBox.ScrollTo(TweetListBox.ListFooter);
                }
            });

        }

        /// <summary>
        /// 可以请求拉取数据
        /// </summary>
        /// <returns></returns>
        private bool IsCanPollData()
        {
            return !isPolling;
        }

        #endregion


        /// <summary>
        /// 获取结束回调
        /// </summary>
        /// <param name="users"></param>
        private void GetFansListEnd(SDK.Objects.ResponseDataObject<SDK.Objects.Tweet> rs)
        {

            isPolling = false;

            isVerticalDrag = false;

            var users = rs.Info;

            hasNext = rs.IsHasNext;

            Dispatcher.BeginInvoke(() =>
            {
                var data = (IEnumerable<SDK.Objects.Tweet>)TweetListBox.ItemsSource;

                if (data != null)
                {
                    data = data.Concat(users).ToList();
                }
                else
                {

                    data = users;
                }

                //处理界面提示

                TweetListBox.ItemsSource = data;

                TweetListBox.UpdateLayout();

                if (hasNext)
                {
                    TweetListBox.ShowListFooter = false;
                    TweetListBox.ListFooterTemplate = (DataTemplate)this.Resources["ListFooterTemplate"];
                }
                else
                {
                    TweetListBox.ShowListFooter = true;
                    TweetListBox.ListFooterTemplate = (DataTemplate)this.Resources["ListFooterNoDataTemplate"];

                }

                TweetListBox.ShowListHeader = false;

                if (afterLoadedCallback != null)
                {
                    afterLoadedCallback(rs);
                }

            });
        }

        /// <summary>
        /// Search
        /// </summary>
        /// <param name="beforeLoading"></param>
        /// <param name="afterCallback"></param>
        public void Search(string keyword, Action beforeLoading = null, Action<object> afterCallback = null)
        {

            if (string.IsNullOrWhiteSpace(keyword))
            {
                return;
            }

            Dispatcher.BeginInvoke(() =>
            {
                TweetListBox.ItemsSource = null;
                TweetListBox.ShowListFooter = false;
                TweetListBox.ShowListHeader = false;
                TweetListBox.ListFooterTemplate = (DataTemplate)this.Resources["ListFooterTemplate"];
            });

            if (beforeLoading != null)
            {
                beforeLoadingCallback = beforeLoading;
                beforeLoading();
            }

            if (afterCallback != null)
            {
                afterLoadedCallback = afterCallback;
            }

            isPolling = true;
            _keyword = keyword;
            pageIndex = 1;
            Dal.Tweet.Instance.Search(keyword, pageIndex, GetFansListEnd);
        }
    }
}
